<?php
class Zendhlt_File_Upload {
	
	private function getUniqueCode($length = "") {   
		$code = md5(uniqid(rand(), true));
	         
		if ($length != "") { 
		 	return substr($code, 0, $length);
		} else {
			return $code;
		}	
	}
	
	/*
	 * param string | Ten tap file field upload 
	 * param string | Duong dan den thu muc upload
	 * param array	| Option of Upload
	 * param string | Ten moi cua file upload
	 */
	public function upload($fileName, $uploadDir, $option = null, $prefix = 'pic_') {
		$upload = new Zend_File_Transfer_Adapter_Http();		
		$upload->setDestination($uploadDir, $fileName);
		$fileInfo = $upload->getFileInfo();
	    
		if($option == null) {
			$newFileName = $fileInfo[$fileName]['name'];
			$upload->receive($fileName);
		}
		
		if($option['task'] == 'rename') {
			$newFileName = $fileInfo[$fileName]['name'];
			preg_match("/\.([^\.]+)$/", $newFileName, $matches); 
			$fileExtension = $matches[1];
			
			// Tao ten tap tin moi			
			do {
				// kiem tra su ton tai cua file, neu chua hop le thi van thuc hien				
				$newFileName = $this->getUniqueCode(25) .  '.' . $fileExtension;
			} while(file_exists($uploadDir . $newFileName));
			
			// upload file
			$upload->addFilter('Rename', array('target' => $uploadDir . $newFileName, 'overwrite' => true));	
			$upload->receive($fileName);
		}
		
    	return $newFileName;
	}
	
	public function resizeImage($fileName, $linkImage, $newImageDir, $width, $height) {
		$img = Zendhlt_File_Image::create($linkImage);
		$img->resize($width, $height);
		$img->save($newImageDir . $fileName);
	}
	
	public function format(&$files) {
		$names = array('name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);
		
		foreach ($files as $key => $part) {
			// only deal with valid keys and multiple files
		    $key = (string) $key;
		    
		    if (isset($names[$key]) && is_array($part)) {
	            foreach ($part as $position => $value) {
	                $files[$position][$key] = $value;
	            }
	            
	            // remove old key reference
	            unset($files[$key]);
	        }
	    }
	}
	
}
?>